package org.hoyi.microservice;

import java.util.ArrayList;
import java.util.List;

import org.hoyi.microservice.routes.model.HoyiProvider;
import org.hoyi.microservice.routes.model.HoyiRouter;

/**
 * 当前调度器的服务管理.
 * @author sam
 *
 */
public class HoyiServiceManagement {

   private static HoyiServiceManagement _instance;
 
   public static HoyiServiceManagement getInstance()
   {
     if (_instance == null) {
       _instance = new HoyiServiceManagement();
     }
     return _instance;
   }
   /**
    * 服务供应器。
    */
    List<HoyiProvider> services ;

	public List<HoyiProvider> getProviders() {
		if(services == null)
			services = new ArrayList<>();
		return services;
	}
	
	public void setPoviders(List<HoyiProvider> services) {
		if (services == null) {
			services = new ArrayList<>();
		}
		this.services = services;
	}
	
	public void AddProvider(HoyiProvider provider) {
		getProviders().add(provider);
	}
	
	/**
	 * 路由器，用nginx做路由器和负载.
	 */
	List<HoyiRouter> routers;

	public List<HoyiRouter> getRouters() {
		if (routers == null) {
			routers = new ArrayList<>();
		}
		return routers;
	}
	/**
	 * 根据路由ID获取路由
	 * @param ServiceID
	 * @return value
	 */
	public HoyiRouter getRouters(String ServiceID) {
		for (HoyiRouter router : HoyiServiceManagement.getInstance().getRouters()) {
			if(router.getServiceID().equals(ServiceID)) {
				return router;
			}
		}
		return null;
	}
	
	public void setRouters(List<HoyiRouter> routers) {
		this.routers = routers;
	}
	
	public void AddRouter(HoyiRouter router) {
		this.getRouters().add(router);
	}
	/**
	 * 根据ServiceID获取Provider.
	 * @param ServiceID
	 * @return value
	 */
	public List<HoyiProvider> GetProviderByID(String ServiceID) {
		List<HoyiProvider> providers = new ArrayList<>();
		for (HoyiProvider provider : HoyiServiceManagement.getInstance().getProviders()) {
			if(provider.getServiceID().equals(ServiceID)) {
				providers.add(provider);
			}
		}
		return providers;
	}
   
	/**
	 * 根据ServiceID获取Provider
	 * 注意ServiceID不要带空格.
	 * 
	 * @param ServiceIDs
	 * @return value
	 */
	public List<HoyiProvider> GetProvider(String ServiceIDs){
		List<HoyiProvider> providers = new ArrayList<>();

		if (ServiceIDs.trim().length() > 0) {
			if(ServiceIDs.contains(",")) {
				String[] ids = ServiceIDs.split(",");
				for (String id : ids) {
					providers = HoyiServiceManagement.getInstance().GetProviderByID(id);
				}
			}else {
				providers = HoyiServiceManagement.getInstance().GetProviderByID(ServiceIDs);
			}
		}
		return providers;
	}
	
}
